import React, { useState, useEffect, useRef, useMemo, useCallback, Fragment } from 'react'
import { Tabs, Calendar } from 'antd-mobile';
import H5Model from 'modules/cooperationDetails/components/h5Detail/index';
import MemberModel from 'modules/cooperationDetails/components/memberDetail/index';
import ConsumeModel from 'modules/cooperationDetails/components/consume/index';
import  lovelornManager , {PromoteUserDetailVO}from 'api/lovelorn-manager'
import './details.scss'
import Item from 'antd-mobile/lib/popover/Item';
import { WithLogin } from 'modules/user/LoginContext'
const DetailsModel: PageComponent = props => {
    let originbodyScrollY = document.getElementsByTagName('body')[0].style.overflowY;
    const radios = [
        { label: '注册量', value: 0 },
        { label: '注册用户消费额', value: 1 }
    ];
    const now = new Date();
    const [tabs, setTabs] = useState([{title: '个人'}]);
    const [showCalendar, setShowCalendar] = useState(false);
    const [currentTabIndex, setCurrentTabIndex] = useState(0);
    const [radioItemValue, setRadioItemValue] = useState(0);
    const [valueCalendar, setValueCalendar] = useState([]);
    //const [currentPageNumber, setCurrentPageNumber] = useState(1)//页码
    const [memberTotal, setMemberTotal] = useState(-1)
    const [moneyTotal, setMoneyTotal] = useState(0.00)
    const [appRegisteTotal, setAppRegisteTotal] = useState(0.00)
    
    const [isGroup, setIsGroup] = useState(false);
   
    var curPage = useRef(1)//页码
    var pullRefreshHeight = useRef(0)
    var pullToRefreshRef = useRef(null)
    const currntRefreshing = useRef(false)
    var valueCalendarRef=useRef(null);
    const [listData, setListData] = useState([])

    useEffect(() => {
        let docId=document.getElementById("details-model")
        //curPage.current = currentPageNumber
        pullRefreshHeight.current = docId.scrollHeight;
        currntRefreshing.current = false;
        valueCalendarRef.current=valueCalendar;
    })

    
    
    useEffect(() => {
        let loginVo = WithLogin.getShareState();
        if(!(loginVo&&loginVo.user)){
            return;
        }
        let phone=loginVo.user.userPhone;
        lovelornManager.bdAccounts.isBdleaderPhone({phone:phone}).then((res)=>{
            console.log("re",res)
            if(res){//是组长
                setIsGroup(true);
                const tabs_group = [
                    { title: '个人' },
                    { title: '小组' },
                    { title: 'h5统计' }
                ];
                setTabs(tabs_group)
            }else{//不是组长
                setIsGroup(false)
                setTabs([{ title: '个人' }, { title: 'h5统计' }])
            }
        })
        // 获取第一页数据
        //getDataByPage(1, radioItemValue);
    }, [])
    useEffect(()=>{
        // 获取第一页数据也在这里
        getDataByPage(radioItemValue)
    },[radioItemValue,currentTabIndex])
    
    //  分页获取数据
    var dataList: any[] = []
    const getDataByPage = ( radioItemValue: number) => {
       console.log("getDataByPage",radioItemValue)
       let loginVo = WithLogin.getShareState();
       if(!(loginVo&&loginVo.user)){
        return;
       }
       var params = {
            pageNo: curPage.current,
            pageSize: 10,
            param:{}
       };
       if(tabs[currentTabIndex].title=='h5统计'){
        params = {
            pageNo: curPage.current,
            pageSize:10,
            param: {
                promoteUserId: loginVo.user.userId,//282381969358848
                isGroup:isGroup,
            }
        }
        if(valueCalendarRef.current[0]){
            let obj={
                startTime:valueCalendarRef.current[0],
                endTime:valueCalendarRef.current[1]
            }
            Object.assign(params.param,obj)
        }
        lovelornManager.promoteRegisterInfo.wxListPage(params).then((res:any) => {
            console.log("listdata",res)
            var arr:PromoteUserDetailVO[] = []
            if(res&&res.entities&&res.entities.length>0){
                setListData(c=> c.concat(res.entities))
                curPage.current=curPage.current+1;
            }
            setMemberTotal(res&&res.count||0)
            currntRefreshing.current=false
            
        })
        //app注册总数
        lovelornManager.promoteRegisterInfo.wxCountAppRegister(params).then((res:any)=>{
            console.log("111",res)
            setAppRegisteTotal(res||0)
        })
        return;
       }
        params = {
            pageNo: curPage.current,
            pageSize: 10,
            param: {
                promoteUserId: loginVo.user.userId,//282381969358848
                isGroup:isGroup,
            }

        }
        if(valueCalendarRef.current[0]){
            let obj={
                startTime:valueCalendarRef.current[0],
                endTime:valueCalendarRef.current[1]
            }
            Object.assign(params,obj)
        }
        if(radioItemValue==radios[0].value){//引流
            lovelornManager.promoteUserDetails.wxListPage(params).then((res:any) => {
                console.log("listdata",res)
                var arr:PromoteUserDetailVO[] = []
                if(res&&res.entities&&res.entities.length>0){
                    setListData(c=> c.concat(res.entities))
                    curPage.current=curPage.current+1;
                    //setCurrentPageNumber(currentPage+1)
                }
                setMemberTotal(res&&res.count||0)
                currntRefreshing.current=false
                
            })
        }else{//消费额
            lovelornManager.promoteUserConsumeDetails.wxListPage(params).then((res:any) => {
                console.log("listdata",res)
                var arr:PromoteUserDetailVO[] = []
                if(res&&res.entities&&res.entities.length>0){
                    setListData(c=> c.concat(res.entities))
                    curPage.current=curPage.current+1;
                }
                setMemberTotal(res&&res.count||0)
                currntRefreshing.current=false
                
            })
            //获取消费额总数
            lovelornManager.promoteUserConsumeDetails.wxTotalMoney(params).then((res:any)=>{
                console.log("111",res)
                setMoneyTotal(res||0.00)
            })
        }
        
    }
    // 定义刷新方法
    const onRefreshList = useCallback(() => {
        let docId=document.getElementById("details-model")
        if (currntRefreshing.current) {
            return
        }
        currntRefreshing.current=true;
        var scrollTop =
            window.pageYOffset ||
            docId.scrollTop ||
            docId.scrollTop;
        //可视区域
        const domHeight = document.compatMode == "CSS1Compat"
            ? document.documentElement.clientHeight
            : document.body.clientHeight;
        // 文档高度
        const height = docId.scrollHeight;
        console.log("1111pullRefreshHeight",pullRefreshHeight.current)
        if (scrollTop + domHeight >= height - 80) {
            console.log(' 上拉到底了',scrollTop)
            getDataByPage( radioItemValue)
        } else if (scrollTop + domHeight < height - 80) {
            currntRefreshing.current=false;
        }
    }, [radioItemValue,getDataByPage])
    useEffect(() => {
        let docId=document.getElementById("details-model")
        docId.addEventListener('scroll', onRefreshList,false)
        return () => {
            docId.removeEventListener('scroll', onRefreshList,false)
		}
    },[onRefreshList])

    const changeTabs = (index: number) => {
        console.log("changeTabs")
        setCurrentTabIndex(index);
        curPage.current=1;
        setListData([])
        setValueCalendar([]);
        setRadioItemValue(radios[0].value);
        //getDataByPage(1, radios[0].value)

    }
    const toShowCalendar = () => {
        setShowCalendar(true);
    }
    const toSearch = () => {
        curPage.current=1;
        setListData([])
        getDataByPage(radioItemValue)
    }
    const changeRadios = (value: number) => {
        console.log("ccc", value,currentTabIndex)
        curPage.current=1;
        setRadioItemValue(value)
        setValueCalendar([])
        setListData([])
        //getDataByPage(1, value);
    }
    
    const onCancel = () => {
        document.getElementsByTagName('body')[0].style.overflowY = originbodyScrollY;
        setShowCalendar(false);
        setValueCalendar([])
    }
    const toDouble=(n:number)=>{
        if(n<10){
            return "0"+n;
        }
        return n;
    }
    const formatDate = (t: any) => {
        console.log("ttt", t, t.getDate())
        let year = t.getFullYear();
        let month = toDouble(t.getMonth() + 1);
        let day = toDouble(t.getDate());
        return year + '-' + month + '-' + day
    }
    const onConfirm = (startTime: any, endTime: any) => {
        console.log("111", startTime, endTime)
        document.getElementsByTagName('body')[0].style.overflowY = originbodyScrollY;
        setShowCalendar(false);

        setValueCalendar([formatDate(startTime), formatDate(endTime)])
    }

    return (
        <div className="details-model" id="details-model">
            <div className="tabContent">
                <div className="tabsBox flexR">
                    {
                        tabs.map((item, index) => (
                            <div className={`tabItem ${index == currentTabIndex ? 'active' : ''}`} key={index}
                                onClick={() => { changeTabs(index) }}
                            >{item.title}</div>
                        ))
                    }
                </div>
                <div className="calendarBox flexR">
                    <div className="calendarInfo flexR" onClick={toShowCalendar}>
                        {
                            valueCalendar[0]
                                ? <Fragment><span className="startTime">{valueCalendar[0]}</span><span className="depart">~</span><span className="endTime">{valueCalendar[1]}</span></Fragment>
                                : <Fragment><span className="startHolder">起始时间</span><span className="depart">~</span><span className="endHolder">结束时间</span></Fragment>
                        }
                        <img className="calendarImg" src={require('../../../assets/image/cooperationDetails/calendar_icon.png')}></img>
                    </div>
                    <div className="searchBox flexR" onClick={toSearch}>
                        <img src={require('../../../assets/image/cooperationDetails/search.png')}></img>
                    </div>
                </div>
                
            </div>
            {
                tabs[currentTabIndex].title=='h5统计'?
                <div className="h5ListBox">
                    <div className="flexR numberBox">
                        <div className="numberText flexR">
                            <div>
                                <span>H5页面手机号提交总数：</span>
                                <span className="num">{memberTotal>0?memberTotal:0}</span>
                            </div>
                            <div>
                                <span>APP注册总数：</span>
                                <span className="num">{appRegisteTotal>0?appRegisteTotal:0}</span>
                            </div>
                            <img className="icon" src={require('../../../assets/image/cooperationDetails/icon.png')}></img>
                        </div>
                    </div>
                    <H5Model listData={listData} totalListLength={memberTotal} isGroup={isGroup} currentTabIndex={currentTabIndex}/>
                </div>
                :
                <div className="listBox">
                <div className="radioBox flexR">
                        {
                            radios.map(i => (
                                <div key={i.value} className={`radioItem ${radioItemValue === i.value ? 'active' : ''}`} onClick={() => { changeRadios(i.value) }}>
                                    {i.label}
                                </div>
                            ))
                        }
                    </div>

                    {
                        radioItemValue == radios[0].value && <Fragment>
                            <div className="flexR numberBox">
                                <p className="numberText flexR">
                                    {
                                        currentTabIndex==0?<span>我所推广的总人数：</span>:<span>我小组推广的注册总人数：</span>
                                    }
                                    <span className="num">{memberTotal>0?memberTotal:0}</span>
                                    <img className="icon" src={require('../../../assets/image/cooperationDetails/icon.png')}></img>
                                </p>
                            </div>
                            <MemberModel listData={listData} totalListLength={memberTotal} currentTabIndex={currentTabIndex}/>
                        </Fragment>
                        
                    }
                    {
                        radioItemValue == radios[1].value && <Fragment>
                            <div className="flexR numberBox">
                                <p className="numberText flexR">
                                    {
                                        currentTabIndex==0?<span>我所推广注册用户的消费总额：</span>:<span>我小组所推广注册用户的消费额：</span>
                                    }
                                    <span className="num">{moneyTotal}元</span>
                                    <img className="icon" src={require('../../../assets/image/cooperationDetails/icon.png')}></img>
                                </p>
                            </div>
                            <ConsumeModel listData={listData} totalListLength={memberTotal} currentTabIndex={currentTabIndex}/>
                        </Fragment>
                    }
            </div>
            }
            <Calendar
                visible={showCalendar}
                onCancel={onCancel}
                onConfirm={onConfirm}
                defaultValue={valueCalendar[0]&&[new Date(valueCalendar[0]),new Date(valueCalendar[1])]}
                defaultDate={new Date(+now - 15552000000)}
                minDate={new Date(+now - 93312000000)}
                maxDate={new Date(+now)}
            />
        </div>
    )
}
DetailsModel.options = { disableHeader: true, wrapperClassName: '' }
export default DetailsModel